package com.unitymarvel.harmonyos.projects.findme.common;

import com.unitymarvel.harmonyos.projects.findme.MainAbility;
import com.unitymarvel.harmonyos.projects.findme.slice.SettingsAbilitySlice;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
///////////////////////////////////////////////////
// 项目的详细实现过程：https://ke.qq.com/course/3677276?tuin=a22a65ce
// 关注微信公众号和B站，获取更多鸿蒙学习资源
// 微信公众号：极客起源
// B站：https://space.bilibili.com/477001733
//
// 作者:李宁（蒙娜丽宁）
//
// 版本: 1.0
// Copyright (C), 2001-2022, 李宁
// 程序被版权法保护
//
///////////////////////////////////////////////////

public class DistributedGameServices {
    private static ServerSocket serverSocket;
    private static Thread thread;
    private static List<Thread> clientThreads = new ArrayList<>();
    public static Map<String, DeviceData> deviceDataMap = new HashMap<>();
    public static class DeviceData {
        public Socket socket;
        public int widgetCount;
    }
    private MainAbility context;

    public DistributedGameServices(MainAbility context) {
        this.context = context;
        try {
            if (serverSocket == null) {
                serverSocket = new ServerSocket(8888);
            }
        } catch (Exception e) {

        }
    }

    public void startServer() {
        if (thread == null) {

            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            context.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    //   Tools.showTip(context, "开始监听");
                                }

                            });
                            final Socket socket = serverSocket.accept();
                            DeviceData deviceData = new DeviceData();
                            deviceData.socket = socket;
                            deviceDataMap.put(socket.getInetAddress().getHostAddress(), deviceData);

                            OutputStream os = socket.getOutputStream();
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                            //向服务器端发送一条消息
                            bw.write("widget_count:\n");
                            bw.flush();

                            try (InputStream input = socket.getInputStream()) {
                                System.out.println("client socket:" + socket.getInetAddress().getHostAddress());
                                BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
                                for (; ; ) {
                                    final String line = reader.readLine();
                                    // 获取客户机中当前widget的数量
                                    if(line.startsWith("widget_count:")) {
                                        int widgetCount = Integer.parseInt(line.substring("widget_count:".length()));

                                        deviceData = DistributedGameServices.deviceDataMap.get(socket.getInetAddress().getHostAddress());
                                        deviceData.widgetCount = widgetCount;

                                    } else if(line.startsWith("score:")) {
                                        MainAbility.score += 5;
                                        context.updateWidget(MainAbility.gamePanelFormId, "score", MainAbility.score);


                                    } else if(line.startsWith("click_char:")) {
                                        String clickChar = line.substring("click_char:".length()).trim();
                                        System.out.println(clickChar + ":" + MainAbility.randomChar);

                                        //if(clickChar.equals(MainAbility.randomChar)) {
                                        if(true) {
                                            MainAbility.score += 5;
                                            context.updateWidget(MainAbility.gamePanelFormId, "score", MainAbility.score);

                                        }


                                    }
                                    final String ss = line;
                                    context.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                        @Override
                                        public void run() {
                                            //  Tools.showTip(context, ss);

                                        }

                                    });

                                }
                            }catch (Exception e) {

                            }



                        } catch (Exception e) {

                        }
                    }
                }
            });
            thread.start();
        }

    }

    public void write(String s) {

        for (DeviceData deviceData:deviceDataMap.values()) {
            Socket socket = deviceData.socket;
            try {

                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
                writer.write(s + "\n");
                writer.flush();


            } catch (Exception e) {

            }
        }
    }

}
